//
//  SpashViewController.swift
//  TimMusic
//
//  Created by nkl on 2024/10/31.
//

import Foundation
import KLExtension

class SpashViewController: UIViewController {
    lazy var logoView: UIImageView = .simpleImage(imageName: "small_logo_ic")
    var timer: Timer?
    var timeRemaining = 3
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        addChildren()
        makeConstraints()

        startCountdown()
    }

    func startCountdown() {
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in
            guard let self = self else { return }
            self.timeRemaining -= 1

            if self.timeRemaining <= 0 {
                timer.invalidate()
                enterApp()
            }
        }
    }

    deinit {
        timer?.invalidate() // 确保定时器在控制器释放时被销毁
    }

    func enterApp() {
        guard let appDelegate = UIApplication.shared.delegate,
              let keyWindow = appDelegate.window else {
            return
        }

        if !(keyWindow?.rootViewController is TMTabbarViewController) {
            setRootToTabBarController(in: keyWindow)
        }
    }

    // 将设置根视图控制器的逻辑分离成单独的方法
    private func setRootToTabBarController(in window: UIWindow?) {
        let vc = TMTabbarViewController()
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
    }

    func addChildren() {
        view.addSubview(logoView)
    }

    func makeConstraints() {
        logoView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(150)
        }
    }
}
